package com.imooc.network;

import org.junit.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/** URL网络编程
 * 1. URL统一资源定位符，对应着互联网的某一资源地址
 * 2. 格式： http://localhost:8080/example/beauty.jpg?username=tom
 *          协议    主机名   端口号 资源地址
 *
 * @Date:2021/10/21/20:31
 * @Description:
 */
public class URLTest {

    @Test
    public void test01() throws MalformedURLException {
        URL url = new URL("http://localhost:8080/examples/javase.jpg");
        System.out.println(url.getProtocol());  //获取URL协议的协议名
        System.out.println(url.getHost());      //获取该URL的主机名
        System.out.println(url.getPort());      //获取该url的端口号
        System.out.println(url.getPath());     //获取该url的文件名
        System.out.println(url.getFile());     // 获取该url的查询名
    }


    //从服务器下载文件
    @Test
    public void test02() {
        HttpURLConnection urlConnection = null; //获取 url的连接对象
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            URL url = new URL("http://localhost:8080/examples/javase.jpg");

            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.connect();

            inputStream = urlConnection.getInputStream();

            fileOutputStream = new FileOutputStream(new File("javase.jpg"));

            byte[] buffer = new byte[1024];
            int len;
            while((len=inputStream.read(buffer) ) !=-1 ){

                fileOutputStream.write(buffer,0,buffer.length);

            }

            System.out.println("下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileOutputStream !=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream !=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(urlConnection !=null){
                urlConnection.disconnect();
            }
        }

    }

}
